<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :change-page="changePage"
        :editFunc="handleEdit"
        :tableRowClassName="tableRowClassName"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd"
            >新增</el-button
          >
        </template>
        <!-- 时长 -->
        <template #duration="{ rows }">
          <div>{{ secondsToHms(rows.duration) }}</div>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      />
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData" @closeDialogP="visible1 = false">
        <!-- 歌曲波形图 -->
        <template #oscillogramJsonUrl="{ rows }">
          <div ref="waveform">
            <span style="display: none">{{ initBoXingTu(rows) }}</span>
          </div>
        </template>
        <!-- 时长 -->
        <template #duration="{ rows }">
          <div>{{ secondsToHms(rows.duration) }}</div>
        </template>
        <!-- 歌曲/专辑封面 -->
        <template #coverUrl="{ rows }">
          <el-image v-if="rows.coverUrl && rows.coverUrl.indexOf('http') !== -1"
            :src="rows.coverUrl" fit="cover" class="avatar"></el-image>
        </template>
        <!-- 歌曲文件地址 -->
        <template #fileUrl="{ rows }">
          <a
            :href="rows.fileUrl"
            target="_blank"
            v-if="
              rows.haveSongFile === 1 &&
              rows.fileUrl &&
              rows.fileUrl.indexOf('http') !== -1
            "
            >{{ rows.fileUrl }}</a
          >
          <span v-else-if="rows.haveSongFile === 0" class="redTishi"
            >音频文件地址有误，请重新上传正确的地址</span
          >
          <span v-else class="redTishi">暂无信息</span>
        </template>
      </TableDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { User } from "@/types/user";
import axios from "axios";
import {
  fetchSongTrackFileList,
  fetchSongTrackFileCreate,
  fetchSongTrackFileDelete,
  fetchGetObsUrl,
} from "@/api/musicLibrary";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import { FormOption, FormOptionList } from "@/types/form-option";
import { useRouter } from "vue-router";
import { onMounted } from "vue";
import { watchEffect } from "vue";
import WaveSurfer from "wavesurfer.js";

const props = defineProps({
  songId: {
    type: String,
    required: true,
  },
  type: {
    type: Number,
    required: true,
  },
  isDrawer: {
    type: Boolean,
    required: true,
  },
});

// 时长换算
const secondsToHms = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

// 查询相关
const query = reactive({
  keyword: "",
});
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "名称：", prop: "keyword" },
]);
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "songId", label: "歌曲ID", width: 150 },
  { prop: "songTrackFileName", label: "名称", width: 200 },
  { prop: "bpm", label: "BPM", width: 150 },
  { prop: "duration", label: "时长", width: 150 },
  { prop: "createTime", label: "创建时间", width: 150 },
  { prop: "operator", label: "操作", width: 300, fixed: "right" },
]);
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const getData = async () => {
  // 获取前一个页面的参数
  console.log("选中的歌曲id");
  console.log(props.songId);
  let params = {
    currPage: page.currPage,
    size: page.size,
    keyword: query.keyword,
    songId: props.songId,
    type: props.type,
  };
  const res = await fetchSongTrackFileList(params);
  console.log("获取子版本列表");
  console.log(res.data);
  let records = res.data.data.records;
  records.forEach((item) => {
    item.songFileUrl = item.fileUrl;
  });
  tableData.value = records;
  page.total = res.data.data.total;
  console.log(page.total);
};

watchEffect(() => {
  console.log(`Current message is: ${props.isDrawer}`);
  if (props.isDrawer) {
    getData();
  }
});

// 分页
const changePage = (val: number) => {
  console.log("点击分页---歌单分类管理");

  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "120px",
  span: 24,
  list: [
    {
      type: "input",
      label: "名称",
      prop: "songTrackFileName",
      required: true,
      placeholder: "请输入名称",
    },
    {
      type: "uploadSong",
      label: "歌曲文件地址",
      prop: "songFileUrl",
      required: true,
    },
    {
      type: "upload",
      label: "封面",
      prop: "coverUrl",
    },
  ],
});
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

// 新增
const handleAdd = (row) => {
  console.log("新增");
  rowData.value = { ...row };
  isEdit.value = false;
  visible.value = true;
};

// 编辑
const handleEdit = (row) => {
  console.log("编辑");
  rowData.value = { ...row };
  isEdit.value = true;
  visible.value = true;
};
const updateData = async (data) => {
  const loading = ElLoading.service({
    lock: true,
    text: "保存中",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let datas = {};
  let obj = {
    songId: props.songId,
    type: props.type,
    fileUrl: data.songFileUrl,
    songTrackFileName: data.songTrackFileName,
    coverUrl: data.coverUrl,
  };
  let editObi = { songTrackFileId: data.songTrackFileId };
  if (isEdit.value) {
    datas = { ...obj, ...editObi };
  } else {
    datas = { ...obj };
  }
  console.log("最终编辑或者新增的数据---是");
  console.log(datas);
  const res = await fetchSongTrackFileCreate(datas);
  loading.close();
  // console.log("新增子版本或者分轨文件");
  // console.log(res.data);
  if (res.data.code == 0) {
    ElMessage.success("成功");
    getData();
  } else {
    ElMessage.error(res.data.msg);
  }
  closeDialog();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});

const waveform = ref(null);
const wavesurfer = ref(null);
const handleView = (row) => {
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: "songId",
      label: "歌曲ID",
    },
    {
      prop: "songTrackFileName",
      label: "名称",
    },
    {
      prop: "oscillogramJsonUrl",
      label: "歌曲波形图",
    },
    {
      prop: "bpm",
      label: "BPM",
    },
    {
      prop: "duration",
      label: "时长",
    },
    {
      prop: "fileUrl",
      label: "歌曲文件地址",
    },
    {
      prop: "coverUrl",
      label: "封面",
    },
    {
      prop: "createTime",
      label: "创建时间",
    },
  ];
  visible1.value = true;
};

const initBoXingTu = async (songInfo) => {
  wavesurfer.value = WaveSurfer.create({
    container: waveform.value,
    progressColor: "#F92E53", // 未播放波形的颜色
    waveColor: "#999999",
    // 波形图的高度，单位为px
    height: 60,
    // 波形的振幅（高度），默认为1
    barHeight: 0.5,
    // 波形条的圆角
    barRadius: 2,
    // 波形条的宽度
    barWidth: 1,
    // 波形条间的间距
    barGap: 0,
    // 播放进度光标条的颜色
    cursorColor: "#999999",
    // 播放进度光标条的宽度，默认为1
    cursorWidth: 0,
    interact: false, // 禁用所有交互
  });
  if (songInfo.fileUrl.indexOf("http") == -1) {
    console.log("需要通过key来获取歌曲路径");
    const res = await fetchGetObsUrl({ key: songInfo.fileUrl });
    console.log(res);
    if (res.data.code === 0) {
      wavesurfer.value.load(
        res.data.data,
        getJsonData(songInfo.oscillogramJsonUrl)
      );
    }
  } else {
    wavesurfer.value.load(
      songInfo.fileUrl,
      getJsonData(songInfo.oscillogramJsonUrl)
    );
  }
};
const getJsonData = (jsonUrl) => {
  axios
    .get(jsonUrl)
    .then((response) => {
      return response.data;
    })
    .catch((error) => {
      console.error("There was an error!", error);
    });
};
// 波形图相关---------------------end

// 删除相关
const handleDelete = async (row) => {
  console.log("删除");
  console.log(row);
  let datas = {
    id: row.songTrackFileId,
  };
  const res = await fetchSongTrackFileDelete(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  if (row.haveSongFile === 0) {
    return "success-row";
  }
  return "";
};
</script>

<style scoped></style>
